﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BDS3M.Controls
{
    public partial class BoxSendMail : System.Web.UI.UserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["Username"] == null)
            {
                Response.Redirect("/home");
            }

            if (!Page.IsPostBack)
            {
                txtTo.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSend.ClientID + "')");
                txtSuject.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSend.ClientID + "')");
                CKEditorNoidung.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSend.ClientID + "')");
            }
        }


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            txtTo.Text = "";
            txtSuject.Text = "";
            CKEditorNoidung.Text = "";
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            string sendto = txtTo.Text;
            string subject = txtSuject.Text;
            string content = CKEditorNoidung.Text;
            string id_from = Session["Employee_ID"].ToString();

            int nextid = Convert.ToInt32(DAL.DCollector.DBCollector.Instance.getNextID("tbl_Message", "Message_ID"));
            DataTable dt = DAL.DCollector.DBCollector.Instance.StoredSelectAllTableWhereName("tbl_Employee", "Employee_User", sendto.ToString());
            DataTable checkuser = DAL.DCollector.DBCollector.Instance.StoredProcedureCheckUsername(sendto);

            if (checkuser.Rows[0]["result"].ToString() != "0")
            {
                if (dt.Rows.Count > 0)
                {
                    int idnextmessage = nextid + 1;
                    string id_to = dt.Rows[0]["Employee_ID"].ToString();
                    string value = "" + idnextmessage + ", " + id_to + ", " + id_from + ", N'" + subject + "', N'" + content + "', N'Unread', '" + DateTime.Now.ToString() + "' ";
                    List<string> values = new List<string>();
                    values.Add(value);
                    DAL.DCollector.DBCollector.Instance.Insert("tbl_Message", values, true);
                    txtTo.Text = "";
                    txtSuject.Text = "";
                    CKEditorNoidung.Text = "";
                    Response.Write("<script> alert('Gửi thành công !') </script>");
                }
                else
                {
                    Response.Write("<script> alert('Lỗi ! Bãn hãy thử lại !') </script>");
                }
            }
            else
            {
                Response.Write("<script>  alert('Địa chỉ người gửi không tồn tại')</script>");
            }


           
        }


    }
}